﻿using GraphQL.Builders;
using GraphQL.Types;
using System.Reflection;

namespace GraphQLDemo.Api.GroupTypes
{
    public enum PortalType
    {
        Client,
        Admin
    }

    public static class PortalsExtensions
    {
        public static PortalType CurrentPortal = PortalType.Client;

        public static void ApplyPortal<T>(this FieldType fieldType, ObjectGraphType<T> graphType, params PortalType[] portalTypes)
        {
            if (portalTypes.Any() && !portalTypes.Contains(CurrentPortal))
            {
                var propertyInfo = graphType.Fields
                    .GetType()
                    .GetProperty("List", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                var fieldValue = propertyInfo.GetValue(graphType.Fields);
                var methodInfo = propertyInfo.PropertyType.GetMethod("Remove");
                methodInfo.Invoke(fieldValue, new object[]
                {
                    fieldType
                });
            }
        }

        public static void ApplyPortal<TSourceType, TReturnType, TOrigin>(this FieldBuilder<TSourceType, TReturnType> fieldBuilder, ObjectGraphType<TOrigin> graphType, params PortalType[] portalTypes)
        {
            if (portalTypes.Any() && !portalTypes.Contains(CurrentPortal))
            {
                var propertyInfo = graphType.Fields
                    .GetType()
                    .GetProperty("List", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                var fieldValue = propertyInfo.GetValue(graphType.Fields);
                var methodInfo = propertyInfo.PropertyType.GetMethod("Remove");
                methodInfo.Invoke(fieldValue, new object[]
                {
                    fieldBuilder.FieldType
                });
            }
        }

    }
}
